import hashlib
import http
import json
import random
import urllib
from utils.JSON的输入和输出 import 读取json, 写入json
from pygoogletranslation import Translator
from volcengine.ApiInfo import ApiInfo
from volcengine.Credentials import Credentials
from volcengine.ServiceInfo import ServiceInfo
from volcengine.base.Service import Service

translator = Translator(service_url='translate.google.cn')


def googleTranslate(translate_text: str) -> str:
    return translator.translate(translate_text, src='ja', dest='zh-CN').text


def baiduTranslate(translate_text, flag=0):
    appid = '20210911000940733'  # 填写你的appid
    secretKey = 'fgR436NKnKbqJ_rFF_6g'  # 填写你的密钥
    httpClient = None
    myurl = '/api/trans/vip/translate'  # 通用翻译API HTTP地址
    fromLang = 'jp'  # 原文语种

    if flag:
        toLang = 'jp'  # 译文语种
    else:
        toLang = 'zh'  # 译文语种

    salt = random.randint(3276, 65536)

    sign = appid + translate_text + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(translate_text) + '&from=' + fromLang + \
            '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign # noqa

    # 建立会话，返回结果
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)

        # return result
        return result['trans_result'][0]['dst']

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()


def volcengineTranslate(s: str) -> str:
    import json

    k_access_key = 'AKLTZTdkZmM1YTg4NDY4NDkwYzgzNmZhY2U0MDY5NWUwMGE'
    k_secret_key = 'TVRCa1lUTXpNekZoWlRJME5HVTNOemxqTjJKa05UVTFPREF3WldGaFpXSQ=='
    k_timeout = 5  # second
    k_service_info = \
        ServiceInfo('open.volcengineapi.com',
                    {'Content-Type': 'application/json'},
                    Credentials(k_access_key, k_secret_key, 'translate', 'cn-north-1'),
                    5,
                    5)
    k_query = {'Action': 'TranslateText', 'Version': '2020-06-01'}
    k_api_info = {'translate': ApiInfo('POST', '/', k_query, {}, {})}
    service = Service(k_service_info, k_api_info)
    body = {
        'SourceLanguage': 'ja',
        'TargetLanguage': 'zh',
        'TextList': [s],
    }
    res = service.json('translate', {}, json.dumps(body))
    return json.loads(res)['TranslationList'][0]['Translation']


# print(volcengineTranslate('こんにちは世界'))

if __name__ == '__main__':
    name = 'IDS_ACCOUNTBAN'
    l = 读取json(f'output/IDS_To_JSON/{name}.json')
    for index, item in enumerate(l):
        if index > 1:
            if item['source'] == 'coming soon' or item['source'].startswith(
                    '<card'):
                item['trans'] = item['source']
                continue
            if item['trans']: continue
            item['trans'] = volcengineTranslate(item['source'])
            # print(item['trans'])
            # item['trans'] = baiduTranslate(item['source'])
            print(index * 5 + 1)
            写入json(l, f'output/IDS_To_JSON/{name}.json')
    写入json(l, f'output/IDS_To_JSON/{name}.json')
